import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {CommonTool} from '../common/common.tool';
import {HTTP_URLS} from './base-http.url';
import {environment} from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class BaseService {

  constructor(private http: HttpClient) {

  }

  /**
   *  获取token
   */
  public getToken(code) {
    const url = CommonTool.analysisParam(HTTP_URLS.getToken, {code});
    return this.http.get(url);
  }

  /***
   * 获取系统菜单
   */
  public getSystemMenuList(): Observable<any> {
    const url = CommonTool.analysisUrl(HTTP_URLS.getSystemMenuList, {systemCode: environment.systemCode});
    return this.http.get(url);
  }

  /**
   * 菜单处理
   */
  public menuHandle(array, authorityCodes) {
    array = this.getMenus(array, authorityCodes);
    const menus = [];
    for (const arr of array) {
      menus.push({
        id: arr.id,
        title: arr.name,
        icon: arr.icon,
        url: arr.url,
        parentId: arr.parentId,
        seq: arr.seq,
        open: false,
        selected: false,
        disabled: false
      });
    }
    return this.getTreeSort('root', menus);
  }

  /**
   * 获取菜单
   */
  public getMenus(menus: Array<any>, authorityCodes: Array<any>) {
    const result = [];
    for (const authorityCode of authorityCodes) {
      for (const menu of menus) {
        if (authorityCode === menu.code) {
          result.push(menu);
        }
      }
    }
    return result;
  }

  /**
   * 获取树排序
   */
  public getTreeSort(parentId, menus) {
    const trees = [];
    const array = this.getTrees(parentId, menus);
    for (const arr of array) {
      const children = this.getTreeSort(arr.id, menus);
      if (children != null && children.length > 0) {
        arr.children = children;
      }
      trees.push(arr);
    }
    trees.sort((a, b) => {
      if (a.seq != null && b.seq != null) {
        return a.seq - b.seq;
      }
      return 1;
    });
    return trees;
  }

  /**
   * 获取树集合
   */
  public getTrees(parentId, menus) {
    const array = [];
    for (const menu of menus) {
      if (parentId === menu.parentId) {
        array.push(menu);
      }
    }
    return array;
  }
}
